package com.digital.smartgrow.service.datacenter.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.digital.smartgrow.common.util.MD5Util;
import com.digital.smartgrow.dao.datacenter.TeacherMapper;
import com.digital.smartgrow.dto.datacenter.TeacherPageDTO;
import com.digital.smartgrow.entity.datacenter.Teacher;
import com.digital.smartgrow.entity.expert.Expert;
import com.digital.smartgrow.service.datacenter.TeacherService;
import com.github.benmanes.caffeine.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xiewb
 * @since 2022-04-03
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {

    @Autowired
    private Cache<String, Teacher> teacherCache;

    @Override
    public Object getListByPage(TeacherPageDTO pageDTO) {
        Page<Teacher> page = new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize());
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(pageDTO.getStatus()), "status", pageDTO.getStatus());
        queryWrapper.like(StringUtils.isNotBlank(pageDTO.getEmployeeId()), "employeeId", pageDTO.getEmployeeId());
        queryWrapper.like(StringUtils.isNotBlank(pageDTO.getName()), "name", pageDTO.getName());
        return this.page(page, queryWrapper);
    }

    @Override
    public Teacher getInfo(Integer id) {
        return this.getById(id);
    }

    @Override
    public Teacher getInfoByUserName(String employeeId) {
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Teacher::getEmployeeId, employeeId);
        return this.getOne(queryWrapper);
    }

    @Override
    public Teacher login(Teacher teacher) {
        String token = MD5Util.MD5(teacher.getEmployeeId() + System.currentTimeMillis());
        teacher.setToken(token);
        teacher.setPassword(null);
        teacher.setSalt(null);
        teacherCache.put(token, teacher);
        return teacher;
    }

    /**
     * 专家登录
     *
     * @param expert
     * @return
     */
    @Override
    public Teacher login(Expert expert) {
        Teacher teacher=new Teacher();
        teacher.setId(expert.getId());
        teacher.setName(expert.getName());
        teacher.setIsExport(true);
        String token = MD5Util.MD5(expert.getEmployeeId() + System.currentTimeMillis());
        teacher.setToken(token);
        teacher.setPassword(null);
        teacher.setSalt(null);
        teacherCache.put(token, teacher);
        return teacher;
    }
}
